<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use backend\behaviors\SearchBehavior;
use yii\data\ActiveDataProvider;
use common\models\News;

/**
 * NewsSearch represents the model behind the search form about `common\models\News`.
 */
class NewsSearch extends News
{
  public $created_at_start;
  public $created_at_end;
    /**
    * @inheritdoc
    */
    public function attributeLabels()
    {
      return array_merge(
        parent::attributeLabels(),
        [
          'created_at_start' => '开始时间',
          'created_at_end' => '结束时间',
        ]
      );
    }
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'catid', 'listorder', 'created_at', 'updated_at', 'deleted', 'click_num'], 'integer'],
            [['title', 'image', 'keywords', 'description', 'content', 'source'], 'safe'],
            [['created_at_start','created_at_end'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
    * @param array() $params
    * @param int $pageSize
    * @param int $f 0|1
    * @return ActiveDataProvider
    */
    public function search($params,$pageSize = 20,$f = 0)
    {
        $query = News::find($f);

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => &$query,
            'pagination' => ['pageSize'=>$pageSize],
            'sort'=>[
                'defaultOrder'=>[
                    'id'=> SORT_DESC,
                ],
            ],
        ]);

        $this->load($params);

      if ($this->validate()) {

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'catid' => $this->catid,
            'listorder' => $this->listorder,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
            'deleted' => $this->deleted,
            'click_num' => $this->click_num,
        ]);

        $query->andFilterWhere(['like', 'title', $this->title])
            ->andFilterWhere(['like', 'image', $this->image])
            ->andFilterWhere(['like', 'keywords', $this->keywords])
            ->andFilterWhere(['like', 'description', $this->description])
            ->andFilterWhere(['like', 'content', $this->content])
            ->andFilterWhere(['like', 'source', $this->source]);


        if(!empty($this->created_at_start) && !empty($this->created_at_end)){
          $query->andFilterWhere(['between', $this->a.'.created_at', strtotime($this->created_at_start),strtotime($this->created_at_end)]);
        }
      }
      return $dataProvider;
    }
}
